package org.hxzon.tapestry5.components;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.util.BigDecimalUtil;

public class PercentFormatter {

    @Parameter(required = true)
    private BigDecimal part;
    @Parameter(required = true)
    private BigDecimal total;
    @Parameter(value = "#.####", defaultPrefix = BindingConstants.LITERAL)
    private String format;
    @Inject
    private Locale locale;

    @BeginRender
    void beginRender(MarkupWriter writer) {
        NumberFormat f = NumberFormat.getInstance(locale);
        if (f instanceof DecimalFormat) {
            ((DecimalFormat) f).applyPattern(format);
        }
        writer.write(f.format(BigDecimalUtil.divide(part.multiply(BigDecimalUtil.Int100), total)));
        writer.write("%");
    }
}
